<template>
  <vue-content>
    <vue-header>
      <vue-header-form>
        <el-form :inline="true" :model="formFilter" ref="formFilter">
          <el-form-item label="电子券名称" prop="couponName">
            <el-input v-model.trim="formFilter.couponName" style="width:150px"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="formFilter.type" style="width:200px" placeholder="请选择电子券类型">
              <el-option label="折扣券" value="rebate"></el-option>
              <el-option label="抵用券" value="voucher"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="SearchSubmit('formFilter')">查询</el-button>
            <el-button @click="resetForm('formFilter')">重置</el-button>
            <el-button type="primary" @click="accredit">发券</el-button>
            <el-button type="primary" @click="create">新增</el-button>
          </el-form-item>
          <br />
          <el-form-item label="使用开始日期" prop="validatyBegin">
				     <div class="block">
							    <el-date-picker
							      v-model.trim="formFilter.validatyBegin"
							      type="date"
							      placeholder="选择日期时间">
							    </el-date-picker>
							  </div>
				  </el-form-item>
		      <el-form-item label="使用结束日期" prop="validatyEnd">
		         <div class="block">
						    <el-date-picker
						      v-model.trim="formFilter.validatyEnd"
						      type="date"
						      placeholder="选择日期时间">
						    </el-date-picker>
						  </div>
		      </el-form-item>
        </el-form>
      </vue-header-form>
    </vue-header>
    <vue-body>
      <div class="content">
        <div class="right_content">
          <el-table
            v-loading.body="loading"
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
              prop="couponName"
              label="电子券名称">
            </el-table-column>
            <el-table-column
              label="类型">
              <template scope="scope">
                {{ scope.row.type | type }}
              </template>
            </el-table-column>
            <el-table-column
              prop="restricted"
              label="抵用券限制金额">
            </el-table-column>
            <el-table-column
              prop="denomination"
              label="面值">
            </el-table-column>
            <el-table-column
              label="电子券状态">
              <template scope="scope">
                {{ scope.row.couponStatus | couponStatus}}
              </template>
            </el-table-column>
            <el-table-column
              prop="num"
              label="总数量">
            </el-table-column>
            <el-table-column
              prop="usedNum"
              label="已发数量">
            </el-table-column>
            <el-table-column
              prop="validatyEnd"
              label="有效期结束日期">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template scope="scope">
                <el-button-group>
                <el-button
                  :disabled="scope.row.status === '1'?true:false"
                  size="small"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                size="small"
                type="primary"
                @click="handleDetail(scope.$index, scope.row, tableData)">详情</el-button>
                <el-button
                  :disabled="scope.row.status === '01'?true:false"
                  size="small"
                  type="info"
                  @click="handlePro(scope.$index, scope.row, tableData)">关联</el-button>
                  </el-button-group>
                </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </vue-body>
    <vue-footer style="padding: 5px 0;margin: 0 -5px;float:right;">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="pageSize">
      </el-pagination>
    </vue-footer>
    <edit-create
      ref="edit-role"
      @close="editFinish"
      :view="view"
      v-if="view ==='create'"/>
    <edit-role
    ref="edit-role"
    @close="editFinish"
    :view="view"
    v-if="view ==='edit'"/>
    <edit-detail
    ref="edit-detail"
    @close="editFinish"
    :view="view"
    v-if="view ==='detail'"/>
  </vue-content>
</template>

<script>
	import {query,create,edit,detail} from '@/services/coupons'
  import {RequestError} from '@/services/errors'
  import {deepClone} from '@/utilities/object'
  import EditRole from './edit'
  import EditCreate from './create'
  import EditDetail from './Detail'
  export default {
    name: 'role-table',
    components: {EditRole,EditDetail,EditCreate},
    data: () => ({
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      formFilter: {
        couponName: "",
        type:"",
        validatyBegin:"",
        validatyEnd:""
      },
      loading: false,
      view: '',
    }),
    methods: {
      async loadData () {
        this.loading = true;
        let reg = RegExp(/T/);
        if(JSON.stringify(this.formFilter.validatyBegin).match(reg)){
          this.formFilter.validatyBegin = this.formatDateTime(this.formFilter.validatyBegin);
        }
        if(JSON.stringify(this.formFilter.validatyEnd).match(reg)){
          this.formFilter.validatyEnd = this.formatDateTime(this.formFilter.validatyEnd);
        }
        try {
        let data = await query(Object.assign({currentPage: this.currentPage},{perPage:10},this.formFilter))
          // debugger
          this.tableData = data.data
          this.pageSize = parseInt(data.totalResult)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      async create () {
        this.view = 'create'
        await this.$nextTick()
      },
      async handleEdit (index, data) {
        // debugger
        this.view = 'edit'
        await this.$nextTick()
        this.$refs['edit-role'].dialogFormVisible = true
        try {
          let formData = await detail(data.id)
          // debugger
          var dateArr = [];
          dateArr = formData.data.useTime.split("-")
          this.$refs['edit-role'].startTime = dateArr[0]
          this.$refs['edit-role'].endTime = dateArr[1]
          this.$refs['edit-role'].couponId = formData.data.couponId
          this.$refs['edit-role'].mchtNo = formData.data.mchtNo
          this.$refs['edit-role'].formData = deepClone(formData.data)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
      },
      async handleDetail (index, data) {
        this.view = 'detail'
        await this.$nextTick()
        this.$refs['edit-detail'].id = data.id
        this.$refs['edit-detail'].loadData()
      },
      async handlePro (index, data) {
				this.$router.push({
	        path: 'coupons/relation', 
	        name: 'relation',
	        query: { 
            id: data.id,
            couponNo: data.couponNo
          }
        })
      },
      SearchSubmit () {
        this.loadData()
      },
      formatDateTime (date) {  
        var y = date.getFullYear();  
        var m = date.getMonth() + 1;  
        m = m < 10 ? ('0' + m) : m;  
        var d = date.getDate();  
        d = d < 10 ? ('0' + d) : d;  
        return y + '-' + m + '-' + d;  
      },
      accredit(){
        this.$router.push({
	        path: 'coupons/accredit', 
	        name: 'accredit',
	        query: { 
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
        this.currentPage = 1
        this.loadData()
      },
      editFinish (needRefresh) {
        this.view = ''
        if (needRefresh) {
          this.loadData()
        }
      }
    },
    watch: {
      currentPage (newVal) {
        this.loadData(newVal)
      }
    },
    filters: {
      promAppro (value) {
      	//发券途径
        return {'general': '普通券'}[value]
      },
      useRule (value) {
      	//使用规则
        return {'D': '和其他优惠券一起使用', 'M': '叠加使用'}[value]
      },
      type (value) {
      	//券类型
        return {'rebate': '折扣券', 'voucher': '抵用券'}[value]
      },
      couponUsedType(value) {
      	//电子券状态
        return {'default': '默认', 'share': '可分享', 'useonly': '只可使用'}[value]
      },
      couponType(value) {
      	//第三方券类型
        return {'default': '默认', 'third': '第三方'}[value]
      },
      thirdType(value) {
      	//使用描述类型
        return {'default': '默认', 'url': '链接'}[value]
      },
      couponStatus(value) {
      	//使用描述类型
        return {'00': '草稿', '01': '券已生效', '02': '过期', '03': '删除'}[value]
      },
    },
    created () {
      this.loadData()
    }
  }
</script>
<style>

</style>
